from lxml import etree
from util.selenium.webdriver.common.by import By
from util.selenium.webdriver.support.wait import WebDriverWait
from util.selenium.webdriver.support import expected_conditions as EC

# from util.db_operate import SaveData, GetTechList
from spider_data.spiderBaseMethod import bm
from util.g import g


# from util.handle_reg import handle_reg


def parse_reg(driver=None):
    try:
        bm.detail_switch_iframe(driver=driver)
        main_case_loc = (By.LINK_TEXT, '注册登记表')

        # # # 点击 主要情况表按钮。

        bm.wait(driver=driver, ele_loc=main_case_loc)

        driver.find_element(*main_case_loc).click()
        # # # 等待标题加载出来
        WebDriverWait(driver=driver, timeout=10, poll_frequency=2).until(
            EC.presence_of_all_elements_located(g.title_loc))
        text = driver.page_source
        text = text.replace('<div class="line"></div>', '')

        tree = etree.HTML(text)
        # content = bm.get_first(tree.xpath('//div[contains(@class, "box-body")]'))
        WriteRegistrationForm = dict()
        reg = parse_reg_save(tree=tree)
        equ = parse_equity_save(tree=tree)

        WriteRegistrationForm.update(reg)
        WriteRegistrationForm.update(equ)
        # driver.switch_to.default_content()
        return {"key": "WriteRegistrationForm", "value": WriteRegistrationForm}
    except Exception as err:
        msg = "error: {} file: {} lines: {}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                    err.__traceback__.tb_lineno)
        g.logger.error(msg)
        raise Exception(msg)


def parse_reg_save(tree=None):
    try:
        scale_name = bm.join_and_repalce(tree.xpath("//div[@id='uniform-saleIncome']/span/text()"))
        scale = scale_name

        #  需要在数据库中查找出分别对应的领域的id。
        domain1 = bm.get_first(li=tree.xpath("//div[@id='uniform-onemain']/span/text()"))
        domain2 = bm.get_first(li=tree.xpath("//div[@id='uniform-scdmain']/span/text()"))
        domain3 = bm.get_first(li=tree.xpath("//div[@id='uniform-thdmain']/span/text()"))
        domain = ",".join([domain1, domain2, domain3])

        gopublic_name = bm.get_first(li=tree.xpath("//input[@checked='checked']/@value"))
        gopublic = 0 if u"否" in gopublic_name or gopublic_name == "0" else 1

        stockcat_name = bm.get_first(li=tree.xpath("//div[@id='uniform-marketList']/span/text()"))
        stockcat = stockcat_name if stockcat_name else None

        gopublictime = bm.str_to_date(s=tree.xpath("//input[@id='marketDate']/@value"))
        stockcode = bm.get_first(tree.xpath("//input[@id='marketCode']/@value"))
        # 经营范围
        opscope = bm.handel_long_text(tree.xpath("//textarea[@id='operation']/text()"))

        entbrief_intro = bm.handel_long_text(tree.xpath("//textarea[@id='companyProfile']/text()"))

        contact = bm.get_first(li=tree.xpath("//input[@id='args1']/@value"))
        contact_phone = bm.get_first(li=tree.xpath("//input[@id='args2']/@value"))
        contact_tel = bm.get_first(li=tree.xpath("//input[@id='args3']/@value"))
        contact_fax = bm.get_first(li=tree.xpath("//input[@id='args4']/@value"))
        contact_email = bm.get_first(li=tree.xpath("//input[@id='args0']/@value"))

        legal_phone = bm.get_first(li=tree.xpath("//input[@id='args10']/@value"))
        legal_tel = bm.get_first(li=tree.xpath("//input[@id='args5']/@value"))
        legal_fax = bm.get_first(li=tree.xpath("//input[@id='args6']/@value"))
        legal_email = bm.get_first(li=tree.xpath("//input[@id='args7']/@value"))
        dom = bm.get_first(li=tree.xpath("//input[@id='args8']/@value"))
        WriteRegistrationForm = {"scale": scale, "hitech_field_namelist": domain, "gopublic": gopublic,
                                 "gopublic_name": gopublic_name, "stockcat": stockcat, "gopublictime": gopublictime,
                                 "stockcode": stockcode, "stockcat_name": stockcat_name, 'contact': contact,
                                 'contact_phone': contact_phone, 'contact_tel': contact_tel, 'contact_fax': contact_fax,
                                 'contact_email': contact_email, 'legal_phone': legal_phone, 'legal_tel': legal_tel,
                                 'legal_fax': legal_fax, 'legal_email': legal_email, "dom": dom, "opscope": opscope,
                                 "entbrief_intro": entbrief_intro}
        return {"WriteRegistrationForm": WriteRegistrationForm}
    except Exception as err:
        msg = "error: {} file: {} lines: {}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                    err.__traceback__.tb_lineno)
        g.logger.error(msg)
        raise Exception(msg)


def parse_equity_save(tree=None):
    try:
        citizen = tree.xpath('.//tbody[@id="personTypeTbodyId"]/tr[not(@class)]')
        WriteCivilType = list()
        for c in citizen:
            ty = c.xpath('./td[1]/div[@class="selector"]/span/text()')
            name = c.xpath('./td[2]/input/text()')
            id_num = c.xpath('./td[3]/input/text()')
            invest = c.xpath('./td[4]/input/text()')
            c_item = {'type': ty, 'name': bm.join_and_repalce(name), 'id_num': bm.join_and_repalce(id_num),
                      'invest': bm.get_float(float_str=invest)}
            WriteCivilType.append(c_item)
            # SaveData().save(table='ent_equity_citizen', value=c_item)

        legal = tree.xpath('.//tbody[@id="companyTypeTbodyId"]/tr[not(@class)]')
        WriteLegalType = list()
        for l in legal:
            ty = l.xpath('./td[1]/div[@class="selector"]/span/text()')
            name = l.xpath('./td[2]/input/text()')
            code = l.xpath('./td[3]/input/text()')
            invest = l.xpath('./td[4]/input/text()')
            l_item = {'type': ty, 'name': bm.join_and_repalce(name), 'code': bm.join_and_repalce(code),
                      'invest': bm.get_float(float_str=invest), 'is_risk': 0}
            WriteLegalType.append(l_item)

        risk = tree.xpath('.//div[@id="entMontyId"]//tbody/tr[not(@class)]')
        WriteVentureInvestment = list()
        for r in risk:
            ty = r.xpath('./td[1]/div[@class="selector"]/span/text()')
            name = r.xpath('./td[2]/input/text()')
            code = r.xpath('./td[3]/input/text()')
            invest = r.xpath('./td[4]/input/text()')
            l_item = {'type': ty, 'name': bm.join_and_repalce(name), 'code': bm.join_and_repalce(code),
                      'invest': bm.get_float(float_str=invest), 'is_risk': 1}
            WriteVentureInvestment.append(l_item)
        return {"WriteCivilType": WriteCivilType, "WriteLegalType": WriteLegalType,
                "WriteVentureInvestment": WriteVentureInvestment}
    except Exception as err:
        msg = "error: {} file: {} lines: {}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                    err.__traceback__.tb_lineno)
        g.logger.error(msg)
        raise Exception(msg)


if __name__ == '__main__':
    li = ["contact", "contact_phone", "contact_tel", "contact_fax", "contact_email", "legal_phone", "legal_tel",
          "legal_fax", "legal_email"]
